﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace DataApplication
{
    public class Log
    {
        private static Boolean isUsing = false;
        public static void Write(LogType type, string input)
        {
            while (isUsing)
            {
                System.Threading.Thread.Sleep(50);
            }
            isUsing = true;
            try
            {
                string path = String.Format("{0}\\Log\\{1}\\", Directory.GetCurrentDirectory(), DateTime.Now.ToString("yyMMdd"));
                string filePath = String.Format("{0}{1}.txt", path, type.ToString());
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                FileInfo fileInfo = new FileInfo(filePath);
                if (!fileInfo.Exists)
                {
                    FileStream fs;
                    fs = File.Create(filePath);
                    fs.Close();
                    fileInfo = new FileInfo(filePath);
                }

                if (fileInfo.Length > 1024 * 1024 * 1)
                {
                    ///文件超过10MB则重命名
                    File.Move(filePath, String.Format("{0}{1}{2}.txt", path, type.ToString(), DateTime.Now.ToString("HHmmss")));
                }

                using (FileStream fs = fileInfo.OpenWrite())
                {
                    /**/
                    ///根据上面创建的文件流创建写数据流
                    StreamWriter w = new StreamWriter(fs);

                    /**/
                    ///设置写数据流的起始位置为文件流的末尾
                    w.BaseStream.Seek(0, SeekOrigin.End);

                    ///写入当前系统时间并换行
                    w.Write("{0}: \r\n", DateTime.Now.ToString("HH:mm:ss"));

                    /**/
                    ///写入日志内容并换行
                    w.Write(input + "\r\n\r\n");

                    /**/
                    ///清空缓冲区内容，并把缓冲区内容写入基础流
                    w.Flush();

                    /**/
                    ///关闭写数据流
                    w.Close();
                }
            }
            catch (Exception) { }

        }
    }

    public enum LogType
    {
        Log,
        Error,
        Fatal
    }
}
